using System.Linq;
using System.Threading.Tasks;
using Zhongjiu.IRepository;
using Zhongjiu.IRepository.Blog;
using Zhongjiu.IServices;
using Zhongjiu.Model.Blog;

namespace Zhongjiu.Services
{
  /// <summary>
  /// sysUserInfoServices
  /// </summary>	
  public partial class SysUserInfoServices : BaseServices<SysUserInfo, ISysUserInfoRepository>, ISysUserInfoServices
  {
    private readonly IBaseRepository<UserRole> _userRoleRepository;
    private readonly IBaseRepository<Role> _roleRepository;
    public SysUserInfoServices(IBaseRepository<UserRole> userRoleRepository, IBaseRepository<Role> roleRepository)
    {
      _userRoleRepository = userRoleRepository;
      _roleRepository = roleRepository;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="loginName"></param>
    /// <param name="loginPwd"></param>
    /// <returns></returns>
    public async Task<SysUserInfo> SaveUserInfo(string loginName, string loginPwd)
    {
      SysUserInfo sysUserInfo = new SysUserInfo(loginName, loginPwd);
      SysUserInfo model = new SysUserInfo();
      var userList = await base.Query(a => a.LoginName == sysUserInfo.LoginName && a.LoginPWD == sysUserInfo.LoginPWD);
      if (userList.Count > 0)
      {
        model = userList.FirstOrDefault();
      }
      else
      {
        var id = await base.Add(sysUserInfo);
        model = await base.QueryById(id);
      }

      return model;

    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="loginName"></param>
    /// <param name="loginPwd"></param>
    /// <returns></returns>
    public async Task<string> GetUserRoleNameStr(string loginName, string loginPwd)
    {
      string roleName = "";
      var user = (await base.Query(a => a.LoginName == loginName && a.LoginPWD == loginPwd)).FirstOrDefault();
      var roleList = await _roleRepository.Query(a => a.IsDeleted == false);
      if (user != null)
      {
        var userRoles = await _userRoleRepository.Query(ur => ur.UserId == user.Id);
        if (userRoles.Count > 0)
        {
          var arr = userRoles.Select(ur => ur.RoleId.ToString()).ToList();
          var roles = roleList.Where(d => arr.Contains(d.Id.ToString()));

          roleName = string.Join(',', roles.Select(r => r.Name).ToArray());
        }
      }
      return roleName;
    }
  }
}

//----------sysUserInfo结束----------
